<template>
  <div class="flink-cluster-container">
    <!-- 可折叠的页面标题和统计信息 -->
    <div class="page-header" :class="{ collapsed: headerCollapsed }">
      <div class="header-background">
        <div class="bg-pattern"></div>
        <div class="bg-gradient"></div>
      </div>
      
      <div class="page-title">
        <div class="title-icon">
          <div class="icon-container" style="width: 36px; height: 36px; background: linear-gradient(135deg, #ff6b6b 0%, #ff8e53 100%); border-radius: 8px; color: white; box-shadow: 0 2px 8px rgba(255, 107, 107, 0.2);">
            <el-icon size="20"><DataBoard /></el-icon>
            <div class="icon-glow"></div>
          </div>
        </div>
        <div class="title-content">
          <div class="title-main">
            <h1>Flink集群管理</h1>
            <div class="title-badge">
              <el-icon><Star /></el-icon>
              <span>Cluster</span>
            </div>
          </div>
          <p class="page-description">
            <el-icon><Monitor /></el-icon>
            管理和监控Flink集群，支持多环境切换和实时状态查看
          </p>
          <div class="title-meta">
            <div class="meta-item">
              <el-icon><Connection /></el-icon>
              <span>集群监控</span>
            </div>
            <div class="meta-item">
              <el-icon><Switch /></el-icon>
              <span>环境切换</span>
            </div>
            <div class="meta-item">
              <el-icon><View /></el-icon>
              <span>实时预览</span>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 集群状态统计 -->
      <div class="page-stats">
        <div class="stat-card running">
          <div class="stat-icon">
            <el-icon><VideoPlay /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ currentEnv ? (clusterStats.runningJobs || 0) : '-' }}</div>
            <div class="stat-label">运行中作业</div>
            <div class="stat-trend">
              <el-icon><Menu /></el-icon>
              <span>{{ currentEnv ? '活跃' : '未连接' }}</span>
            </div>
          </div>
        </div>
        
        <div class="stat-card taskmanager">
          <div class="stat-icon">
            <el-icon><Cpu /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ currentEnv ? (clusterStats.taskManagers || 0) : '-' }}</div>
            <div class="stat-label">TaskManagers</div>
            <div class="stat-trend">
              <el-icon><Monitor /></el-icon>
              <span>{{ currentEnv ? '正常' : '未连接' }}</span>
            </div>
          </div>
        </div>
        
        <div class="stat-card total">
          <div class="stat-icon">
            <el-icon><Grid /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ currentEnv ? (clusterStats.totalSlots || 0) : '-' }}</div>
            <div class="stat-label">总槽位</div>
            <div class="stat-trend">
              <el-icon><Menu /></el-icon>
              <span>{{ currentEnv ? '配置' : '未连接' }}</span>
            </div>
          </div>
        </div>
        
        <div class="stat-card available">
          <div class="stat-icon">
            <el-icon><CircleCheck /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ currentEnv ? (clusterStats.availableSlots || 0) : '-' }}</div>
            <div class="stat-label">可用槽位</div>
            <div class="stat-trend">
              <el-icon><Check /></el-icon>
              <span>{{ currentEnv ? '空闲' : '未连接' }}</span>
            </div>
          </div>
        </div>
      </div>
      
    </div>

    <!-- Flink UI嵌入区域 -->
    <div class="flink-ui-container" v-if="currentEnv">
      <div class="ui-header">
        <h3>
          <el-icon><Monitor /></el-icon>
          Flink Dashboard
        </h3>
        <div class="ui-actions">
          <!-- 环境切换器 -->
          <el-select 
            v-model="currentEnvId" 
            placeholder="选择Flink环境"
            @change="handleEnvChange"
            class="env-select-compact"
            popper-class="env-select-popper"
          >
            <template #prefix>
              <el-icon><Connection /></el-icon>
            </template>
            <el-option
              v-for="env in flinkEnvironments"
              :key="env.id"
              :label="env.config_name"
              :value="env.id"
            >
              <span class="env-option-simple">{{ env.config_name }}</span>
              <span class="env-option-detail">{{ env.host }}:{{ env.port }}</span>
            </el-option>
          </el-select>
          
          <!-- 服务控制按钮 -->
          <el-button 
            @click="showOperationDialog('start')" 
            size="small"
            type="success"
          >
            <el-icon><VideoPlay /></el-icon>
            启动
          </el-button>
          <el-button 
            @click="showOperationDialog('stop')" 
            size="small"
            type="danger"
          >
            <el-icon><VideoPause /></el-icon>
            停止
          </el-button>
          <el-button 
            @click="showOperationDialog('restart')" 
            size="small"
            type="warning"
          >
            <el-icon><Refresh /></el-icon>
            重启
          </el-button>
          
          <!-- 刷新和链接按钮 -->
          <el-button 
            @click="refreshCluster" 
            :loading="loading"
            size="small"
            type="primary"
            circle
          >
            <el-icon><Refresh /></el-icon>
          </el-button>
          <el-button 
            @click="openInNewTab" 
            size="small"
            circle
            :type="isConnected ? 'success' : 'danger'"
          >
            <el-icon><Link /></el-icon>
          </el-button>
          
          <!-- 全屏/退出全屏按钮 -->
          <el-button 
            @click="headerCollapsed = !headerCollapsed" 
            size="small"
            circle
            :type="headerCollapsed ? 'info' : ''"
            :title="headerCollapsed ? '退出全屏' : '全屏显示'"
          >
            <el-icon>
              <component :is="headerCollapsed ? 'Minus' : 'FullScreen'" />
            </el-icon>
          </el-button>
        </div>
      </div>
      
      <div class="iframe-wrapper" v-loading="iframeLoading">
        <iframe
          v-if="flinkUrl"
          :src="flinkUrl"
          :key="flinkUrl"
          @load="onIframeLoad"
          @error="onIframeError"
          frameborder="0"
          width="100%"
          height="800"
          class="flink-iframe"
          sandbox="allow-same-origin allow-scripts allow-popups allow-forms"
        ></iframe>
        
        <el-empty 
          v-else 
          description="请选择一个Flink环境"
          :image-size="200"
        />
      </div>
      
      <!-- 连接失败提示 -->
      <div v-if="!isConnected && currentEnv" class="connection-error">
        <el-alert
          title="无法连接到Flink集群"
          type="warning"
          :description="`请检查 ${currentEnv.host}:${currentEnv.port} 是否可访问，或者网络配置是否正确`"
          show-icon
          :closable="false"
        >
          <template #default>
            <div class="error-actions">
              <el-button size="small" @click="refreshCluster">重试连接</el-button>
              <el-button size="small" @click="openInNewTab">在新标签页打开</el-button>
            </div>
          </template>
        </el-alert>
      </div>
    </div>

    <!-- 服务操作对话框 -->
    <el-dialog 
      v-model="showOperationDialogFlag" 
      :title="operationDialogTitle"
      width="500px"
      :close-on-click-modal="false"
    >
      <div class="operation-dialog-content">
        <el-alert 
          :title="operationDialogAlert.title"
          :type="operationDialogAlert.type"
          :description="operationDialogAlert.description"
          show-icon
          :closable="false"
          style="margin-bottom: 20px"
        />
        
        <div class="service-selection">
          <div class="selection-header">
            <el-checkbox 
              v-model="selectAllChecked" 
              @change="handleSelectAllChange"
              :indeterminate="isIndeterminate"
            >
              选择要{{ currentOperation === 'start' ? '启动' : currentOperation === 'stop' ? '停止' : '重启' }}的服务
            </el-checkbox>
          </div>
          <el-checkbox-group v-model="selectedServices" @change="handleServiceChange">
            <el-checkbox label="jobmanager" border>
              <div class="service-option">
                <el-icon><Cpu /></el-icon>
                <span>JobManager</span>
                <el-tag size="small" type="primary">{{ currentEnv.host }}:{{ currentEnv.port }}</el-tag>
              </div>
            </el-checkbox>
            
            <!-- 动态显示真实的TaskManager列表 -->
            <el-checkbox 
              v-for="(tm, index) in taskManagerList" 
              :key="tm.id"
              :label="`taskmanager-${tm.id}`" 
              border
            >
              <div class="service-option">
                <el-icon><Grid /></el-icon>
                <span>TaskManager {{ index + 1 }}</span>
                <el-tag size="small" type="success">{{ extractHost(tm.id) }}</el-tag>
                <el-tag size="small" type="info">{{ tm.slotsNumber }} 槽位</el-tag>
                <el-tag size="small" :type="tm.freeSlots > 0 ? '' : 'warning'">空闲 {{ tm.freeSlots }}</el-tag>
              </div>
            </el-checkbox>
            
            <!-- 如果没有获取到TaskManager信息，显示通用选项 -->
            <el-checkbox v-if="taskManagerList.length === 0" label="taskmanager-all" border>
              <div class="service-option">
                <el-icon><Grid /></el-icon>
                <span>所有TaskManager</span>
                <el-tag size="small" type="warning">{{ currentEnv.host }}</el-tag>
              </div>
            </el-checkbox>
          </el-checkbox-group>
        </div>
      </div>
      
      <template #footer>
        <el-button @click="showOperationDialogFlag = false">取消</el-button>
        <el-button 
          type="info"
          @click="showDevTip"
          disabled
        >
          确定{{ currentOperation === 'start' ? '启动' : currentOperation === 'stop' ? '停止' : '重启' }}（开发中）
        </el-button>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  DataBoard, Monitor, Connection, Switch, View, Star,
  Refresh, Link, Setting, VideoPlay, Cpu, Grid, CircleCheck,
  FullScreen, Minus, Menu, Check, Document, ArrowDown, VideoPause
} from '@element-plus/icons-vue'
import api from '@/utils/api'
import { copyToClipboard as copyText } from '@/utils/clipboard'

const router = useRouter()

// 状态管理
const loading = ref(false)
const iframeLoading = ref(false)
const currentEnvId = ref(null)
const flinkEnvironments = ref([])
const clusterStats = ref({
  runningJobs: 0,
  taskManagers: 0,
  totalSlots: 0,
  availableSlots: 0
})
const taskManagerList = ref([]) // TaskManager详细列表
const isConnected = ref(false)
const refreshTimer = ref(null)
const headerCollapsed = ref(true) // 默认折叠介绍卡片
const operationLoading = ref('') // 操作加载状态：'start', 'stop', 'restart'
const showOperationDialogFlag = ref(false)
const currentOperation = ref('') // 当前操作：'start', 'stop', 'restart'
const selectedServices = ref([]) // 选中的服务：['jobmanager', 'taskmanager-xxx']
const selectAllChecked = ref(false) // 全选状态
const isIndeterminate = ref(false) // 半选状态

// 计算属性
const currentEnv = computed(() => {
  return flinkEnvironments.value.find(env => env.id === currentEnvId.value)
})

const flinkUrl = computed(() => {
  if (!currentEnv.value) return ''
  const { protocol, host, port } = currentEnv.value
  return `${protocol || 'http'}://${host}:${port}`
})

const operationDialogTitle = computed(() => {
  const actionMap = {
    'start': '启动Flink集群',
    'stop': '停止Flink集群',
    'restart': '重启Flink集群'
  }
  return actionMap[currentOperation.value] || '集群操作'
})

const operationDialogAlert = computed(() => {
  const alertMap = {
    'start': {
      title: '启动确认',
      type: 'success',
      description: '请选择要启动的服务。启动后服务将开始运行。'
    },
    'stop': {
      title: '停止警告',
      type: 'error',
      description: '停止服务将中断所有运行中的作业，请谨慎操作！'
    },
    'restart': {
      title: '重启提示',
      type: 'warning',
      description: '重启服务将先停止后启动，运行中的作业会被中断。'
    }
  }
  return alertMap[currentOperation.value] || { title: '', type: 'info', description: '' }
})

// 方法
const loadFlinkEnvironments = async () => {
  try {
    loading.value = true
    // 使用settings API获取配置
    const response = await api.get('/settings')
    
    // 处理返回的嵌套数据结构 - response.data.data是实际的数据
    if (response.data && response.data.data && response.data.data.flink) {
      // 将嵌套的对象转换为数组格式
      const flinkConfigs = response.data.data.flink
      flinkEnvironments.value = Object.entries(flinkConfigs).map(([configName, config]) => ({
        // 需要从数据库获取ID，暂时使用配置名称作为ID
        id: configName,
        config_name: configName,
        host: config.host,
        port: config.port,
        protocol: config.protocol || 'http',
        username: config.username || '',
        password: config.password || '',
        database: config.database || '',
        path: config.path || '/',
        description: config.description || '',
        is_active: true, // API返回的都是激活的
        service_type: 'flink'
      }))
      
      // 优先选择FLINK(68)环境，如果没有则选择第一个
      if (flinkEnvironments.value.length > 0 && !currentEnvId.value) {
        const defaultEnv = flinkEnvironments.value.find(env => env.config_name === 'FLINK(68)')
        currentEnvId.value = defaultEnv ? defaultEnv.id : flinkEnvironments.value[0].id
      }
    } else {
      console.warn('未找到Flink环境配置')
      ElMessage.warning('未找到Flink环境配置，请先在三方配置中添加')
    }
  } catch (error) {
    console.error('加载Flink环境失败:', error)
    ElMessage.error('加载Flink环境失败')
  } finally {
    loading.value = false
  }
}

const loadClusterStats = async () => {
  if (!currentEnv.value) return
  
  try {
    // 调用后端API获取集群状态
    const [overviewRes, taskmanagersRes] = await Promise.all([
      api.get('/flink/cluster/overview', {
        params: { 
          config_name: currentEnv.value.config_name,
          host: currentEnv.value.host,
          port: currentEnv.value.port 
        }
      }),
      api.get('/flink/cluster/taskmanagers', {
        params: { 
          config_name: currentEnv.value.config_name,
          host: currentEnv.value.host,
          port: currentEnv.value.port 
        }
      })
    ])
    
    if (overviewRes.data.success) {
      clusterStats.value = overviewRes.data.data
      isConnected.value = true
    }
    
    if (taskmanagersRes.data.success) {
      taskManagerList.value = taskmanagersRes.data.data || []
    }
  } catch (error) {
    console.error('获取集群状态失败:', error)
    isConnected.value = false
  }
}

const handleEnvChange = () => {
  // 清空之前的状态
  clusterStats.value = {
    runningJobs: 0,
    taskManagers: 0,
    totalSlots: 0,
    availableSlots: 0
  }
  isConnected.value = false
  
  // 重新加载集群状态
  loadClusterStats()
  
  // 设置iframe加载状态
  iframeLoading.value = true
}

const refreshCluster = () => {
  loadClusterStats()
  
  // 刷新iframe
  const iframe = document.querySelector('.flink-iframe')
  if (iframe) {
    iframe.src = iframe.src
  }
}

const openInNewTab = () => {
  if (flinkUrl.value) {
    window.open(flinkUrl.value, '_blank')
  }
}

const goToSettings = () => {
  router.push('/third-party-config')
}

// 显示操作对话框
const showOperationDialog = (operation) => {
  if (!currentEnv.value) {
    ElMessage.warning('请先选择一个环境')
    return
  }
  
  currentOperation.value = operation
  // 默认全选所有服务
  selectedServices.value = getAllServices()
  selectAllChecked.value = true
  isIndeterminate.value = false
  showOperationDialogFlag.value = true
}

// 获取所有服务选项
const getAllServices = () => {
  const services = ['jobmanager']
  if (taskManagerList.value.length > 0) {
    taskManagerList.value.forEach(tm => {
      services.push(`taskmanager-${tm.id}`)
    })
  } else {
    services.push('taskmanager-all')
  }
  return services
}

// 处理全选变化
const handleSelectAllChange = (val) => {
  if (val) {
    selectedServices.value = getAllServices()
  } else {
    selectedServices.value = []
  }
  isIndeterminate.value = false
}

// 处理服务选择变化
const handleServiceChange = (value) => {
  const allServices = getAllServices()
  const checkedCount = value.length
  selectAllChecked.value = checkedCount === allServices.length
  isIndeterminate.value = checkedCount > 0 && checkedCount < allServices.length
}

// 从TaskManager ID中提取主机地址
// ID格式：10.1.1.68:38079-f9a975
const extractHost = (tmId) => {
  if (!tmId) return '-'
  const match = tmId.match(/^([^:]+)/)
  return match ? match[1] : tmId.substring(0, 12)
}

// 显示开发中提示
const showDevTip = () => {
  ElMessage.warning({
    message: '该功能正在开发中，敬请期待！',
    duration: 2000
  })
}

// 执行操作（暂未实现）
const executeOperation = async () => {
  showDevTip()
  // TODO: 后续实现SSH控制逻辑
  // if (selectedServices.value.length === 0) {
  //   ElMessage.warning('请至少选择一个服务')
  //   return
  // }
  // 
  // try {
  //   operationLoading.value = currentOperation.value
  //   
  //   const response = await api.post(`/flink/cluster/${currentOperation.value}`, {
  //     config_name: currentEnv.value.config_name,
  //     host: currentEnv.value.host,
  //     port: currentEnv.value.port,
  //     services: selectedServices.value
  //   })
  //   
  //   if (response.data.success) {
  //     const actionText = currentOperation.value === 'start' ? '启动' : 
  //                       currentOperation.value === 'stop' ? '停止' : '重启'
  //     ElMessage.success(response.data.message || `集群${actionText}命令已发送`)
  //     
  //     showOperationDialogFlag.value = false
  //     
  //     const delay = currentOperation.value === 'restart' ? 15000 : 
  //                  currentOperation.value === 'start' ? 8000 : 3000
  //     setTimeout(() => {
  //       refreshCluster()
  //     }, delay)
  //   }
  // } catch (error) {
  //   console.error('操作失败:', error)
  // } finally {
  //   operationLoading.value = ''
  // }
}

// 获取JobManager地址
const getJobManagerUrl = () => {
  if (!currentEnv.value) return '-'
  return `${currentEnv.value.host}:${currentEnv.value.port}`
}

// 获取TaskManager主机列表
const getTaskManagerHosts = () => {
  if (!currentEnv.value) return []
  // 从系统配置或环境配置中获取TaskManager主机列表
  // 这里假设TaskManager与JobManager在同一主机
  // 实际环境中应该从配置中读取
  const host = currentEnv.value.host
  return [`${host}:9249`, `${host}:9250`, `${host}:9251`]
}

// 复制到剪贴板 - 使用统一工具
const copyToClipboard = async (text, label) => {
  await copyText(text, label)
}

// 启动集群
const handleStartCluster = async () => {
  if (!currentEnv.value) {
    ElMessage.warning('请先选择一个环境')
    return
  }
  
  ElMessageBox.confirm(
    `确定要启动 ${currentEnv.value.config_name} 的Flink集群吗？`,
    '启动确认',
    {
      confirmButtonText: '确定启动',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      operationLoading.value = 'start'
      const response = await api.post('/flink/cluster/start', {
        config_name: currentEnv.value.config_name,
        host: currentEnv.value.host,
        port: currentEnv.value.port
      })
      
      if (response.data.success) {
        ElMessage.success('集群启动命令已发送')
        // 等待几秒后刷新状态
        setTimeout(() => {
          refreshCluster()
        }, 3000)
      }
    } catch (error) {
      console.error('启动集群失败:', error)
    } finally {
      operationLoading.value = ''
    }
  }).catch(() => {
    // 用户取消
  })
}

// 停止集群
const handleStopCluster = async () => {
  if (!currentEnv.value) {
    ElMessage.warning('请先选择一个环境')
    return
  }
  
  ElMessageBox.confirm(
    `确定要停止 ${currentEnv.value.config_name} 的Flink集群吗？这将停止所有运行中的作业！`,
    '停止确认',
    {
      confirmButtonText: '确定停止',
      cancelButtonText: '取消',
      type: 'error',
      dangerouslyUseHTMLString: true
    }
  ).then(async () => {
    try {
      operationLoading.value = 'stop'
      const response = await api.post('/flink/cluster/stop', {
        config_name: currentEnv.value.config_name,
        host: currentEnv.value.host,
        port: currentEnv.value.port
      })
      
      if (response.data.success) {
        ElMessage.success('集群停止命令已发送')
        setTimeout(() => {
          refreshCluster()
        }, 3000)
      }
    } catch (error) {
      console.error('停止集群失败:', error)
    } finally {
      operationLoading.value = ''
    }
  }).catch(() => {
    // 用户取消
  })
}

// 重启集群
const handleRestartCluster = async () => {
  if (!currentEnv.value) {
    ElMessage.warning('请先选择一个环境')
    return
  }
  
  ElMessageBox.confirm(
    `确定要重启 ${currentEnv.value.config_name} 的Flink集群吗？这将重启JobManager和TaskManager！`,
    '重启确认',
    {
      confirmButtonText: '确定重启',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      operationLoading.value = 'restart'
      const response = await api.post('/flink/cluster/restart', {
        config_name: currentEnv.value.config_name,
        host: currentEnv.value.host,
        port: currentEnv.value.port
      })
      
      if (response.data.success) {
        ElMessage.success('集群重启命令已发送，请稍候...')
        setTimeout(() => {
          refreshCluster()
        }, 10000) // 重启需要更长时间
      }
    } catch (error) {
      console.error('重启集群失败:', error)
    } finally {
      operationLoading.value = ''
    }
  }).catch(() => {
    // 用户取消
  })
}

const onIframeLoad = () => {
  iframeLoading.value = false
  ElMessage.success('Flink Dashboard加载成功')
}

const onIframeError = () => {
  iframeLoading.value = false
  ElMessage.error('Flink Dashboard加载失败，请检查连接')
  isConnected.value = false
}

// 定时刷新集群状态
const startAutoRefresh = () => {
  refreshTimer.value = setInterval(() => {
    loadClusterStats()
  }, 30000) // 每30秒刷新一次
}

const stopAutoRefresh = () => {
  if (refreshTimer.value) {
    clearInterval(refreshTimer.value)
    refreshTimer.value = null
  }
}

// 生命周期
onMounted(() => {
  loadFlinkEnvironments()
  startAutoRefresh()
})

onUnmounted(() => {
  stopAutoRefresh()
})

// 监听环境变化
watch(currentEnvId, () => {
  if (currentEnvId.value) {
    handleEnvChange()
  }
})
</script>

<style scoped>
.flink-cluster-container {
  padding: 0;
}

/* 页面头部样式 */
.page-header {
  position: relative;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  padding: 20px 24px;
  border-radius: 12px;
  overflow: hidden;
  color: #303133;
  min-height: 120px;
  border: 1px solid #e4e7ed;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

/* 折叠状态 - 完全隐藏 */
.page-header.collapsed {
  display: none;
}

.header-background {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 0;
}

.bg-gradient {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  opacity: 1;
}

.bg-pattern {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-image: 
    radial-gradient(circle at 20% 80%, rgba(255, 107, 107, 0.05) 0%, transparent 50%),
    radial-gradient(circle at 80% 20%, rgba(255, 142, 83, 0.05) 0%, transparent 50%);
  animation: patternMove 30s ease-in-out infinite;
}

@keyframes patternMove {
  0%, 100% { transform: translateX(0) translateY(0); }
  25% { transform: translateX(-10px) translateY(-5px); }
  50% { transform: translateX(5px) translateY(-10px); }
  75% { transform: translateX(-5px) translateY(5px); }
}

.page-title {
  position: relative;
  z-index: 1;
  display: flex;
  align-items: center;
  gap: 24px;
  flex: 1;
}

.title-icon {
  position: relative;
}

.page-header .title-icon .icon-container {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 36px !important;
  height: 36px !important;
  background: linear-gradient(135deg, #ff6b6b 0%, #ff8e53 100%) !important;
  border-radius: 8px !important;
  color: white !important;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(255, 107, 107, 0.2) !important;
}

.page-header .title-icon .icon-container:hover {
  transform: scale(1.05);
  box-shadow: 0 4px 16px rgba(255, 107, 107, 0.3) !important;
}

.page-header .title-icon .icon-glow {
  position: absolute;
  top: -4px;
  left: -4px;
  right: -4px;
  bottom: -4px;
  background: linear-gradient(45deg, rgba(255, 107, 107, 0.2), rgba(255, 142, 83, 0.3));
  border-radius: 12px;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.page-header .title-icon .icon-container:hover .icon-glow {
  opacity: 1;
}

.title-content {
  flex: 1;
}

.title-main {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 12px;
}

.title-main h1 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  letter-spacing: -0.3px;
}

.title-badge {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 4px 8px;
  background: linear-gradient(135deg, #409eff 0%, #66b3ff 100%);
  border-radius: 12px;
  font-size: 11px;
  font-weight: 600;
  color: white;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.page-description {
  margin: 0 0 12px 0;
  color: #606266;
  font-size: 14px;
  font-weight: 400;
  line-height: 1.5;
  display: flex;
  align-items: center;
  gap: 8px;
}

.title-meta {
  display: flex;
  gap: 20px;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 6px;
  color: #909399;
  font-size: 12px;
  font-weight: 500;
}

/* 环境切换器（紧凑版） */
.env-select-compact {
  width: 220px;
}

/* 下拉选项样式 */
.env-option-simple {
  font-weight: 500;
  color: #303133;
}

.env-option-detail {
  margin-left: 12px;
  font-size: 12px;
  color: #909399;
}

/* 下拉弹出层样式 */
:deep(.env-select-popper) {
  .el-select-dropdown__item {
    height: auto;
    padding: 10px 20px;
    line-height: 1.5;
  }
  
  .el-select-dropdown__item.selected {
    font-weight: 600;
  }
}

/* 页面统计卡片 */
.page-stats {
  position: relative;
  z-index: 1;
  display: flex;
  gap: 20px;
}

.stat-card {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 16px;
  background: #fff;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  min-width: 120px;
  position: relative;
  overflow: hidden;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.stat-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.1) 0%, rgba(255, 255, 255, 0.05) 100%);
  opacity: 0;
  transition: opacity 0.3s ease;
}

.stat-card:hover {
  background: #fff;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  border-color: #409eff;
}

.stat-card:hover::before {
  opacity: 1;
}

.stat-icon {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  border-radius: 6px;
  font-size: 16px;
  transition: all 0.3s ease;
}

.stat-card.running .stat-icon {
  background: rgba(103, 194, 58, 0.1);
  color: #67c23a;
}

.stat-card.taskmanager .stat-icon {
  background: rgba(156, 39, 176, 0.1);
  color: #9c27b0;
}

.stat-card.total .stat-icon {
  background: rgba(64, 158, 255, 0.1);
  color: #409eff;
}

.stat-card.available .stat-icon {
  background: rgba(0, 188, 212, 0.1);
  color: #00bcd4;
}

.stat-content {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 4px;
}

.stat-number {
  font-size: 20px;
  font-weight: 700;
  color: #303133;
  line-height: 1;
}

.stat-label {
  font-size: 12px;
  color: #606266;
  font-weight: 500;
}

.stat-trend {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 10px;
  color: #909399;
  font-weight: 500;
}

/* Flink UI容器 */
.flink-ui-container {
  background: white;
  border-radius: 12px;
  overflow: hidden;
  border: 1px solid #e4e7ed;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.ui-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  background: #f8f9fa;
  border-bottom: 1px solid #e4e7ed;
}

.ui-header h3 {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.ui-actions {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

/* 操作对话框 */
.operation-dialog-content {
  padding: 10px 0;
}

.service-selection {
  margin-top: 20px;
}

.selection-header {
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #e4e7ed;
}

.selection-header .el-checkbox {
  font-size: 14px;
  font-weight: 500;
}

.service-option {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
}

.service-option .el-icon {
  font-size: 16px;
}

.service-option span {
  flex: 1;
}

:deep(.el-checkbox.is-bordered) {
  margin-bottom: 12px;
  padding: 10px 15px;
  border-radius: 8px;
  width: 100%;
}

:deep(.el-checkbox-group) {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.iframe-wrapper {
  position: relative;
  background: #fff;
  min-height: 800px;
}

.flink-iframe {
  display: block;
  background: white;
}

/* 当头部完全隐藏时，iframe占满视口 */
.flink-cluster-container:has(.page-header.collapsed) .flink-ui-container {
  margin-top: 0;
}

.flink-cluster-container:has(.page-header.collapsed) .iframe-wrapper {
  min-height: calc(100vh - 120px);
}

.flink-cluster-container:has(.page-header.collapsed) .flink-iframe {
  height: calc(100vh - 120px);
}

/* 连接错误提示 */
.connection-error {
  padding: 20px 24px;
  background: #fff;
}

.error-actions {
  margin-top: 12px;
  display: flex;
  gap: 8px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .page-stats {
    flex-wrap: wrap;
  }
  
  .stat-card {
    flex: 1;
    min-width: calc(50% - 10px);
  }
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    padding: 16px;
    min-height: auto;
  }
  
  .page-title {
    width: 100%;
    margin-bottom: 16px;
  }
  
  .page-stats {
    width: 100%;
    flex-direction: column;
    gap: 12px;
  }
  
  .stat-card {
    width: 100%;
    min-width: auto;
  }
  
  .title-main h1 {
    font-size: 20px;
  }
  
  .ui-header {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }
  
  .ui-actions {
    width: 100%;
    justify-content: space-between;
  }
  
  .env-select-compact {
    flex: 1;
    max-width: 200px;
  }
}
</style>
